source('code/analysis/load.R')

contexts_vector = c('defund'='Experiments 1-2 (defund)', 
                    'amazon'='Auxiliary Experiment 2 (Amazon placebo)',
                    'dst'='Auxiliary Experiment 3 (daylight saving placebo)', 
                    'immigrants'='Experiments 3-4 (deport)')

str_wrap_factor <- function(x, ...) {
  levels(x) <- str_wrap(levels(x), ...)
  x
}

sanctions = haven::read_dta('data/raw/sanctions.dta') %>% 
  filter(attention==1) %>% 
  filter(row_number()<515) %>% 
  mutate(id=row_number()) %>%
  dplyr::select(id, starts_with(c('support', 'backlash')), -ends_with('DO')) %>% 
  mutate_all(as.numeric) %>%
  pivot_longer(-id) %>% 
  separate(name, c('measure','context'), sep='_') %>% 
  mutate(value = as.numeric(value)) %>% 
  pivot_wider(id_cols = c('id', 'context'), values_from = 'value', names_from = c('measure')) %>% 
  group_by(context) %>% 
  drop_na(context) %>%
  summarise(backlash_support = mean((backlash>2)[support==1], na.rm=T),
            n_support = sum(support, na.rm=T),
            backlash_all = mean((backlash>2), na.rm=T),
            n_all = sum(!is.na(backlash)),
            se_support = sd((backlash>2)[support==1], na.rm=T)/sqrt(n_support),
            se_all = sd((backlash>2), na.rm=T)/sqrt(n_support)) %>% 
  mutate(context = recode(context, !!!contexts_vector),
         context = factor(context, levels=(contexts_vector)),
         context = str_wrap_factor(context, 25))
  

plot = ggplot(sanctions, aes(x = context, y = backlash_support)) +
  geom_point(size=3) +
  geom_linerange(aes(ymin = backlash_support-1.96*se_support, ymax=backlash_support+1.96*se_support), alpha=0.3, size=0.8) + 
  theme_bw() +
  theme(axis.title.x = element_blank()) + 
  ylab('Share of supporters expecting backlash') +
  ylim(0,1)

ggsave('output/figures/anticipated-sanctions.png', plot=plot, width=7, height=3.5)

